package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.webSocket.WebSocketServer;
import org.apache.poi.util.Internal;
import org.aspectj.weaver.ast.Or;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WebSocketServer webSocketServer;
    /*
     * 用户下单
     * */
    @Transactional
    public OrderSubmitVO orderSubmit(OrdersSubmitDTO ordersSubmitDTO) {
        // 异常处理,增加代码的健壮性
        // 地址为空的异常处理
        AddressBook address = addressBookMapper.getAddressByID(ordersSubmitDTO.getAddressBookId());
        if (address == null) throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        // 购物车为空异常
        Long userId = BaseContext.getCurrentId();
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.selectShoppingCartByUserId(userId);
        if (shoppingCartList == null || shoppingCartList.isEmpty())
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);

        // 填补订单数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setUserId(userId);
        orders.setConsignee(address.getConsignee());
        orders.setPhone(address.getPhone());
        String addressStr = address.getProvinceName() +
                address.getCityName() +
                address.getDistrictName() +
                address.getDetail();
        orders.setAddress(addressStr);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setOrderTime(LocalDateTime.now());
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setPayStatus(Orders.UN_PAID);
        orderMapper.insert(orders);
        // 插入详情数据
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart cart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        }
        orderDetailMapper.insert(orderDetailList);
        // 清空购物车
        shoppingCartMapper.clearShoppingCartByUserId(orders.getUserId());
        return OrderSubmitVO.builder()
                .id(orders.getId())
                .orderAmount(orders.getAmount())
                .orderNumber(orders.getNumber())
                .orderTime(orders.getOrderTime())
                .build();
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        paySuccess(ordersPaymentDTO.getOrderNumber());
        return new OrderPaymentVO();
        // TODO 下边代码没有密钥等，无法实现，先做一个伪支付成功
        // 当前登录用户id
        /*Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;*/
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);
        Map map = new HashMap();
        map.put("type",1); // 1：表示来单提醒   2：表示客户催单
        map.put("orderId",orders.getId());
        map.put("content","订单号" + outTradeNo);
        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);
    }

    /*
     * 查询订单详情
     * */
    public OrderVO getOrderById(Long id) {
        OrderVO orderVO = new OrderVO();
        Orders orders = orderMapper.selectOrderById(id);
        BeanUtils.copyProperties(orders, orderVO);
        List<OrderDetail> list = orderDetailMapper.selectOrderDetailByOrderId(id);
        orderVO.setOrderDetailList(list);
        return orderVO;
    }

    /*
     * 历史订单查询
     * */
    public PageResult pageSelect(OrdersPageQueryDTO ordersPageQueryDTO) {
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<OrderVO> page = orderMapper.pageSelect(ordersPageQueryDTO);
        long total = page.getTotal();
        List<OrderVO> result = page.getResult();
        for (OrderVO orderVO : result) {
            List<OrderDetail> orderDetailList = orderDetailMapper.selectOrderDetailByOrderId(orderVO.getId());
            orderVO.setOrderDetailList(orderDetailList);
        }
        return new PageResult(total, result);
    }

    /*
     * 取消订单
     * */
    public void cancelOrder(Long id) throws Exception {
        // 根据id查询订单
        Orders ordersDB = orderMapper.selectOrderById(id);

        // 校验订单是否存在
        if (ordersDB == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        if (ordersDB.getStatus() > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orders = Orders.builder()
                .id(id)
                .cancelReason("用户取消订单")
                .cancelTime(LocalDateTime.now())
                .status(Orders.CANCELLED)
                .build();
        // 订单处于待接单状态下取消，需要进行退款
        if (ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            //调用微信支付退款接口
            /*weChatPayUtil.refund(
                    ordersDB.getNumber(), //商户订单号
                    ordersDB.getNumber(), //商户退款单号
                    new BigDecimal(0.01),//退款金额，单位 元
                    new BigDecimal(0.01));//原订单金额
*/
            //支付状态修改为 退款
            orders.setPayStatus(Orders.REFUND);
        }
        orderMapper.update(orders);
    }

    /*
     * 再来一单
     * */
    public void repetitionOrder(Long id) {
        Orders orders = orderMapper.selectOrderById(id);
        List<OrderDetail> orderDetailList = orderDetailMapper.selectOrderDetailByOrderId(id);
        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map(item -> {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(item, shoppingCart);
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCart.setCreateTime(LocalDateTime.now());
            return shoppingCart;
        }).collect(Collectors.toList());
        shoppingCartMapper.insetShoppingCartList(shoppingCartList);
    }

    /*
     * 订单管理接口
     * */
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<OrderVO> page = orderMapper.pageSelect(ordersPageQueryDTO);
        long total = page.getTotal();
        List<OrderVO> result = page.getResult();
        for (OrderVO orderVO : result) {
            List<OrderDetail> orderDetailList = orderDetailMapper.selectOrderDetailByOrderId(orderVO.getId());
            String orderDishes = getOrderDishes(orderDetailList);
            orderVO.setOrderDishes(orderDishes);
        }
        return new PageResult(total, result);
    }

    private String getOrderDishes(List<OrderDetail> orderDetailList) {
        StringBuilder sb = new StringBuilder();
        for (OrderDetail orderDetail : orderDetailList) {
            sb.append(orderDetail.getName() + "*" + orderDetail.getNumber() + ";");
        }
        return sb.toString();
    }

    /*
     * 各个状态的订单数量统计
     * */
    public OrderStatisticsVO getOrderStatistics() {
        Map map = new HashMap();
        map.put("status",Orders.TO_BE_CONFIRMED);
        Integer toBeConfirmed = orderMapper.selectOrderStatusCount(map);
        map.put("status",Orders.CONFIRMED);
        Integer confirmed = orderMapper.selectOrderStatusCount(map);
        map.put("status",Orders.DELIVERY_IN_PROGRESS);
        Integer deliveryInProgress = orderMapper.selectOrderStatusCount(map);
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        return orderStatisticsVO;
    }

    /*
     * 接单
     * */
    public void confirmOrder(OrdersConfirmDTO ordersConfirmDTO) {

        Orders orders = orderMapper.selectOrderById(ordersConfirmDTO.getId());
        if (orders.getStatus().equals(Orders.PENDING_PAYMENT) && orders.getPayStatus().equals(Orders.UN_PAID))
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_PAT);
        BeanUtils.copyProperties(ordersConfirmDTO, orders);
        orders.setStatus(Orders.CONFIRMED);
        orderMapper.update(orders);
    }

    /*
     * 拒单
     * */
    public void rejectionOrder(OrdersRejectionDTO ordersRejectionDTO) {
        Orders orders = Orders.builder()
                .id(ordersRejectionDTO.getId())
                .rejectionReason(ordersRejectionDTO.getRejectionReason())
                .cancelReason("商户拒单")
                .status(Orders.CANCELLED)
                .payStatus(Orders.REFUND)
                .build();
        orderMapper.update(orders);
        // TODO 退款相关操作
    }

    /*
     * 派送订单
     * */
    public void deliveryOrder(Long id) {
        Orders orders = Orders.builder()
                .id(id)
                .status(Orders.DELIVERY_IN_PROGRESS)
                .build();
        orderMapper.update(orders);
    }
    /*
    * 完成订单
    * */
    public void completeOrder(Long id) {
        Orders orders = Orders.builder()
                .id(id)
                .status(Orders.COMPLETED)
                .deliveryTime(LocalDateTime.now())
                .build();
        orderMapper.update(orders);
    }
    /*
    * 商户取消订单
    * */
    public void adminCancelOrder(OrdersCancelDTO ordersCancelDTO) {
        Orders ordersDB = orderMapper.selectOrderById(ordersCancelDTO.getId());
        Orders orders = Orders.builder()
                .id(ordersCancelDTO.getId())
                .cancelReason(ordersCancelDTO.getCancelReason())
                .cancelTime(LocalDateTime.now())
                .status(Orders.CANCELLED)
                .build();
        if (ordersDB.getPayStatus().equals(Orders.PAID)){
            // TODO 退款相关操作
            // 退款成功，更改订单支付状态
            orders.setPayStatus(Orders.REFUND);
        }
        orderMapper.update(orders);
    }

    /*
    * 催单
    * */
    public void reminderOrder(Long id) {
        Orders orders = orderMapper.selectOrderById(id);
        if (orders == null) throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        Map map = new HashMap<>();
        map.put("type",2);
        map.put("orderId",orders.getId());
        map.put("content","订单号" + orders.getNumber());
        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);
    }
}
